java线程池(newSingleThreadExecutor())小应用
创建单个线程,用来操作一个无界的队列任务,不会使用额外的线程。如果线程崩溃会重新创建一个,直到任务完成。
代码:
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Threadd2 { public static void main(String[] args) { ExecutorService es = Executors.newSingleThreadExecutor(); run command = new run(); es.execute(command); es.execute(command); es.shutdown(); } } class run implements Runnable{ @Override public void run() { // TODO Auto-generated method stub try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName()); } }
输出结果:pool-1-thread-1
pool-1-thread-1